package com.eascs.spider.yuqing.worker.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.bson.Document;

import com.eascs.spider.yuqing.common.proj.Platform;
import com.eascs.spider.yuqing.common.util.PropertiesUtil;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class MongodbUtil {
	
	private static MongoClient mongoClient = null;
	private static MongoDatabase mongoDatabase = null;
	
	//公司配置
  static{
        ServerAddress serverAddress = new ServerAddress(
        		PropertiesUtil.getConfig("mongodb.ip"),Integer.valueOf(PropertiesUtil.getConfig("mongodb.port"))); 
        List<ServerAddress> addrs = new ArrayList<ServerAddress>();  
        addrs.add(serverAddress);  
        MongoCredential credential = MongoCredential.createScramSha1Credential(
        		PropertiesUtil.getConfig("mongodb.user"), PropertiesUtil.getConfig("mongodb.library"), 
        		PropertiesUtil.getConfig("mongodb.password").toCharArray());  
        
        List<MongoCredential> credentials = new ArrayList<MongoCredential>();  
        credentials.add(credential);  
        mongoClient = new MongoClient(addrs,credentials);
        mongoDatabase = mongoClient.getDatabase(PropertiesUtil.getConfig("mongodb.library"));
	}
	
	
	private static void set(String collectionName ,Map<String, Object> data){
		MongoCollection<Document> mongoCollection = mongoDatabase.getCollection(collectionName);
		Document document = new Document(data);
		mongoCollection.insertOne(document);
	}
	
	/**
	 * 根据不同平台将数据data存入不同集合
	 * @param data
	 * @param platform
	 */
	public static void setYuqing(Map<String, Object> data , Platform platform){
		set(platform.getPlatform(), data);
	}
	
	/**
	 * 检索指定集合中所有文档
	 * @param collectionName
	 */
	public static List<String> get(String collectionName){
		MongoCollection<Document> mc = mongoDatabase.getCollection(collectionName);
		FindIterable<Document> findIterable = mc.find();  
        MongoCursor<Document> mongoCursor = findIterable.iterator();
        List<String> list = new ArrayList<>();
        while(mongoCursor.hasNext()){  
           Document document = mongoCursor.next();
           list.add(document.getString("url"));
        }
        return list;
	}
	
	public static void main(String[] args) {
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("name", "hzp");
		setYuqing(data, Platform.IFENG_NEWS);
	}
}